<!-- 任务信息弹窗 -->
<script lang="ts" setup>
import { computed, ref } from 'vue'
import type { PropType } from 'vue'
import type { IDbFormItem, IDbSelect } from '@/types/global'
import DuiForm from '@/common-ui/dui-form/index.vue'
import * as taskApi from '@/api/task'
import useNotic from '@/hooks/useNotic'
import { Edit } from '@element-plus/icons-vue'
import type { ITaskInfo } from '../config/type'
import MyCronCore from '../cron-core/index.vue'
import {
  ENUM_TASK_DISPATCH_TYPE,
  TASK_DISPATCH_TYPES,
  ENUM_TASK_RUN_TYPE,
  TASK_RUN_TYPES,
  ENUM_TASK_ROUTER_STRATEGY,
  TASK_ROUTER_STRATEGY_LIST,
  ENUM_TASK_DISPATCH_OUTTIME_STRATEGY,
  TASK_DISPATCH_OUTTIME_STRATEGY_LIST,
  ENUM_TASK_BLOCK_STRATEGY,
  TASK_BLOCK_STRATEGY_LIST
} from '../config/config'

const emits = defineEmits(['refresh'])

const props = defineProps({
  // 标题
  title: {
    type: String,
    default: ''
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  // 执行器列表
  executorList: {
    type: Array as PropType<IDbSelect[]>,
    default() {
      return [] as IDbSelect[]
    }
  }
})
// 详情id
const infoId = ref()
// 弹窗表单数据
const ruleFormRef = ref<InstanceType<typeof DuiForm>>()
// 表单配置
const formConfig = computed<IDbFormItem[]>(() => {
  const configList: IDbFormItem[] = [
    { label: '执行器', prop: 'jobGroup', type: 'select', list: props.executorList, required: true, span: 12 },
    { label: '任务描述', prop: 'jobDesc', type: 'input', required: true, span: 12 },
    { label: '负责人', prop: 'author', type: 'input', required: true, span: 12 },
    { label: '调度类型', prop: 'scheduleType', type: 'select', list: TASK_DISPATCH_TYPES, required: true, span: 12 },
    {
      label: 'cron',
      prop: 'scheduleConf',
      type: 'slot',
      hide: formData.value.scheduleType != ENUM_TASK_DISPATCH_TYPE['CRON'],
      required: formData.value.scheduleType == ENUM_TASK_DISPATCH_TYPE['CRON']
    },
    {
      label: '固定速度',
      prop: 'schedule_conf_FIX_RATE',
      type: 'input',
      hide: formData.value.scheduleType != ENUM_TASK_DISPATCH_TYPE['固定速度'],
      required: formData.value.scheduleType == ENUM_TASK_DISPATCH_TYPE['固定速度']
    },
    { label: '运行模式', prop: 'glueType', type: 'select', list: TASK_RUN_TYPES, required: true, span: 12 },
    { label: 'JobHandler', prop: 'executorHandler', type: 'input', required: true, span: 12 },
    { label: '任务参数', prop: 'executorParam', type: 'textarea' },
    { label: '路由策略', prop: 'executorRouteStrategy', type: 'select', list: TASK_ROUTER_STRATEGY_LIST, span: 12 },
    { label: '子任务ID', prop: 'childJobId', type: 'input', span: 12 },
    { label: '调度过期策略', prop: 'misfireStrategy', type: 'select', list: TASK_DISPATCH_OUTTIME_STRATEGY_LIST, span: 12 },
    { label: '阻塞处理策略', prop: 'executorBlockStrategy', type: 'select', list: TASK_BLOCK_STRATEGY_LIST, span: 12 },
    { label: '任务超时时间', prop: 'executorTimeout', type: 'number', span: 12 },
    { label: '失败重试次数', prop: 'executorFailRetryCount', type: 'number', span: 12 }
  ]
  return configList
})
// 表单默认数据
const defaultData: ITaskInfo = {
  jobGroup: '',
  jobDesc: '',
  author: '',
  scheduleType: ENUM_TASK_DISPATCH_TYPE['无'],
  scheduleConf: '',
  schedule_conf_FIX_RATE: '',
  glueType: ENUM_TASK_RUN_TYPE['BEAN'],
  executorHandler: '',
  executorParam: '',
  executorRouteStrategy: ENUM_TASK_ROUTER_STRATEGY['第一个'],
  childJobId: '',
  misfireStrategy: ENUM_TASK_DISPATCH_OUTTIME_STRATEGY['忽略'],
  executorBlockStrategy: ENUM_TASK_BLOCK_STRATEGY['单机串行'],
  executorTimeout: 0,
  executorFailRetryCount: 0
}
// 表单数据
const formData = ref<ITaskInfo>(JSON.parse(JSON.stringify(defaultData)))
// 是否显示弹窗
const showDialog = ref(false)

/**
 * 打开弹窗并初始化数据
 */
function init(data?: any) {
  infoId.value = data?.id ?? ''
  const resData: any = data || {}
  const defaultForm = JSON.parse(JSON.stringify(defaultData as any))
  Object.keys(defaultForm).forEach((key) => {
    ;(formData.value as any)[key] = resData[key] ?? defaultForm[key]
  })
  showDialog.value = true
}

/**
 * 点击提交
 */
function submitClick() {
  ruleFormRef.value
    ?.validate()
    .then(() => {
      let reqFunc = taskApi.addTaskManage
      let params: any = formData.value
      if (infoId.value) {
        reqFunc = taskApi.editTaskManage
        params = { ...formData.value, id: infoId.value }
      }
      reqFunc(params).then((res) => {
        if (res.success) {
          useNotic().success('提交成功')
          showDialog.value = false
          emits('refresh')
        }
      })
    })
    .catch(() => {})
}

defineExpose({
  init
})
</script>

<template>
  <dui-dialog v-model="showDialog" :title="title">
    <dui-form ref="ruleFormRef" :form-config="formConfig" :form-data="formData" :disabled="disabled">
      <template #scheduleConfSlot>
        <el-input v-model="formData.scheduleConf" disabled placeholder="请选择cron">
          <template #append>
            <el-dropdown>
              <!-- <div class="el-dropdown-link"> -->
              <el-button :icon="Edit" type="primary"></el-button>
              <!-- </div> -->
              <template #dropdown>
                <MyCronCore i18n="cn" maxHeight="350px" v-model:value="formData.scheduleConf" />
              </template>
            </el-dropdown>
          </template>
        </el-input>
      </template>
    </dui-form>
    <template #footer>
      <el-button @click="showDialog = false">取消</el-button>
      <el-button type="primary" @click="submitClick" v-if="!disabled"> 确定 </el-button>
    </template>
  </dui-dialog>
</template>
